package net.xdclass.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.lang.Assert;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.model.LoginUser;

import java.util.Date;

@Slf4j
public class JwtUtil {

    /** token过期时间： 7d */
    private static final long EXPIRE = 60 * 60 * 24 * 7 * 1000;
    /** 密钥 */
    private static final String SECRET = "xdclass.net";
    /** token前缀 */
    private static final String TOKEN_PREFIX = "xdclass";
    /** subject */
    private static final String SUBJECT = "xdclass";

    public static String getJwt(LoginUser user){
        Assert.notNull(user, "user is null.");
        String token = Jwts.builder().setSubject(SUBJECT)
                .claim("head_img", user.getHeadImg())
                .claim("id", user.getId())
                .claim("name", user.getName())
                .claim("mail", user.getMail())
                .claim("ip", user.getIp())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
        return TOKEN_PREFIX + token;
    }

    /**
     * 解析jwt
     * @param token
     * @return
     */
    public static Claims checkJwt(String token){
        try {
            final Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch (Exception e) {
            log.warn("token 解析失败 {}", token);
            return null;
        }
    }

}
